import os
import pyttsx3
import time
from pathlib import Path

def get_files(dir):
    pdir = Path(dir)
    for root, dirs, files in os.walk(pdir):
        for filename in files:
            yield Path(root)/filename

def t2v(ttsx_engine, txt_file, show_txt=False):
    pfile = Path(txt_file).expanduser()
    with open(pfile, 'r') as f:
        txt_content = str(f.read())
        if show_txt:
            print(txt_content)
        if txt_content == '':
            return -1
        # ttsx_engine.say(txt_content)
        ttsx_engine.save_to_file(txt_content, pfile.parent/'{}.mp3'.format(pfile.stem))


if __name__ == '__main__':
    ttsx_engine = pyttsx3.init()
    # getting details of current speaking rate
    rate = ttsx_engine.getProperty('rate')
    print(rate)  # printing current voice rate
    ttsx_engine.setProperty('rate', 160)

    voices = ttsx_engine.getProperty('voices')
    ttsx_engine.setProperty('voice', voices[14].id)

    deal_dir = Path.cwd()
    files = get_files(deal_dir)
    for f in files:
        if f.suffix == '.txt':
            if t2v(ttsx_engine, f)==-1:
                print(f)

    # slide_txt_file = Path.cwd()/'slide_1.txt'
    # t2v(ttsx_engine, slide_txt_file)

    ttsx_engine.runAndWait()
    # while ttsx_engine.isBusy():
        # print(ttsx_engine.isBusy())
    time.sleep(1)


    print('Done!')